package org.september.pisces.filestore.service;

import org.september.core.component.log.LogHelper;
import org.september.core.exception.BusinessException;
import org.september.pisces.filestore.api.FileStoreService;
import org.september.pisces.filestore.entity.FileStoreItem;
import org.september.pisces.filestore.entity.FileStorePool;
import org.september.pisces.filestore.service.hik.ImageClientImpl;
import org.september.pisces.filestore.service.hik.VideoClientImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class HikFileStoreService implements FileStoreService {

    protected LogHelper log = LogHelper.getLogger(this.getClass());


    @Autowired
    private VideoClientImpl videoClient;
    @Autowired
    private ImageClientImpl imageClient;

    @Override
    public String saveWithThumb(FileStorePool pool, byte[] data, String ext, boolean needThumb, float thumbRate) {
        try {
            if (ext.toLowerCase().endsWith("mp4")) {
                return videoClient.uploadVideo(data);
            } else {
                return imageClient.uploadImage(data);
            }
        } catch (Exception e) {
            throw new BusinessException("保存文件失败", e);
        }
    }

    @Override
    public String save(FileStorePool pool, byte[] data, String ext) {
        return saveWithThumb(pool, data, ext, false, 0);
    }

    @Override
    public String getHttpPath(String uuid) {
        return null;
    }


    @Override
    public InputStream getInputStream(FileStorePool pool, FileStoreItem item, boolean thumb) {
        boolean isVideo = item.getExt().toLowerCase().endsWith("mp4");
        if (isVideo) {
            return videoClient.getVideoStream(item.getPath());
        } else {
            return imageClient.getImageStream(thumb ? item.getPath() + "&act=get&ztype=2&zvalue=30" : item.getPath());
        }
    }

    @Override
    public boolean deleteFile(FileStorePool pool, FileStoreItem item) {
        return false;
    }

}
